package com.sunday.common.mq.rabbit.study.spring.study.e2_Sending_Messages;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Declarables;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration
 * https://github.com/openzipkin/brave/blob/master/instrumentation/spring-rabbit/README.md
 */
@Slf4j
@Configuration
public class RabbitConfiguration implements InitializingBean {

    @Autowired
    private CachingConnectionFactory rabbitConnectionFactory;

    @Value("${spring.application.name}")
    private String applicationName;

    public static final String EXCHANGE_NAME = "sending_messages_exchange";
    public static final String ROUTING_KEY_NAME = "sending_messages_routing_key";

    public static final String QUEUE_NAME = "sending_messages_queue";

    @Bean
    public Declarables declarables() {
        return new Declarables(
                new Queue(QUEUE_NAME),
                new DirectExchange(EXCHANGE_NAME),
                new Binding(QUEUE_NAME, Binding.DestinationType.QUEUE, EXCHANGE_NAME, ROUTING_KEY_NAME, null)
        );
    }

    @Override
    public void afterPropertiesSet() {
        rabbitConnectionFactory.setConnectionNameStrategy(connectionFactory -> applicationName);
    }

}
